<template>
  <div class="wallet-connect">
    <button v-if="!userAddress" class="btn" @click="connectWallet">
      🔗 连接钱包
    </button>

    <div v-else class="wallet-info">
      <p>
        <strong class="label">✅ 已连接账户：</strong>
        <span class="addr">{{ userAddress }}</span>
      </p>
      <p>
        <strong class="label">🌐 网络 ID：</strong>
        <span>{{ networkId }}</span>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ethers } from 'ethers';

const userAddress = ref('');
const networkId = ref('');

async function connectWallet() {
  if (window.ethereum) {
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    userAddress.value = accounts[0];
    const provider = new ethers.BrowserProvider(window.ethereum);
    const network = await provider.getNetwork();
    networkId.value = network.chainId.toString();
  } else {
    alert('请先安装 MetaMask 插件');
  }
}

onMounted(() => {
  if (window.ethereum) {
    window.ethereum.on('accountsChanged', accounts => {
      userAddress.value = accounts[0] || '';
    });
    window.ethereum.on('chainChanged', () => {
      window.location.reload();
    });
  }
});
</script>

<style scoped>
.wallet-connect {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  width: 100%;
}

/* 商务风按钮 */
.btn {
  background-color: #27468a;
  color: #fff;
  padding: 12px 0;
  border-radius: 7px;
  border: 1px solid #27468a;
  font-size: 16px;
  font-weight: 500;
  width: 100%;
  min-width: 110px;
  min-height: 42px;
  box-shadow: 0 1px 3px rgba(39,70,138,0.06);
  cursor: pointer;
  transition:
    background 0.18s,
    border 0.18s,
    color 0.18s,
    box-shadow 0.13s;
}
.btn:hover {
  background: #1d335e;
  border-color: #1d335e;
}

/* 钱包信息区块 */
.wallet-info {
  background: #f7f9fb;
  border-radius: 12px;
  border: 1px solid #e5e9ef;
  padding: 16px 16px 10px 16px;
  width: 100%;
  margin-top: 4px;
  box-shadow: 0 2px 10px rgba(50,60,90,0.06);
  font-size: 15px;
  color: #25355a;
}

.wallet-info p {
  margin: 10px 0 4px 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  font-size: 15px;
}
.label {
  color: #27468a;
  min-width: 102px;
  font-weight: 500;
}
.addr {
  word-break: break-all;
  color: #25355a;
  font-size: 15px;
  margin-left: 2px;
}

/* 移动端适配 */
@media (max-width: 640px) {
  .wallet-info {
    padding: 9px 6px 7px 6px;
    font-size: 13.7px;
  }
  .btn {
    font-size: 14px;
    min-height: 36px;
    min-width: 80px;
    padding: 9px 0;
  }
}
</style>
